<template>
  <base-breadcrumb>
    <a-card
      :body-style="{ padding: '24px 32px' }"
      :bordered="false"
    >
      <title-name title="节点信息" />
      <slot name="extraResult" />
      <a-descriptions
        class="mb20"
        title=""
      >
        <a-descriptions-item label="当前节点">
          {{ taskName }}
        </a-descriptions-item>
        <a-descriptions-item label="审批人">
          {{ currentUser.name }}
        </a-descriptions-item>
        <a-descriptions-item label="审批时间">
          {{ currentTime }}
        </a-descriptions-item>
      </a-descriptions>
      <Consultation
        :proc-inst-id="procInstId"
        :is-show-btn="$route.query.isMonitoring ? ($route.query.monitoringType==='process' ? true: false): true"
        :task-name="taskName"
        :sub-approver-list.sync="subApproverList"
      >
        <template slot="approverButton">
          <a-button
            type="primary"
            :loading="loading.PASS"
            @click="handleSave('PASS')"
          >通过</a-button>
          <a-button
            type="primary"
            :loading="loading.REJECT"
            @click="handleSave('REJECT')"
          >驳回</a-button>
        </template>
      </Consultation>
      <title-name title="审批流程信息" />
      <div class="btns-wrapp mb20">
        <a-button
          type="primary"
          @click="visibleState.auditProcess = true"
        > 审批流程图 </a-button>
      </div>
      <a-spin
        tip="流程信息加载中..."
        :spinning="flowRequesting"
      />
      <a-table
        :columns="columnApprove"
        :data-source="approveInfos"
        bordered
      >
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
        <template
          slot="opinions"
          slot-scope="text, record"
        >
          <a-tooltip placement="topLeft">
            <template slot="title">
              <span> {{ record.formData.opinions }}</span>
            </template>
            <span> {{ record.formData.opinions }}</span>
          </a-tooltip>
        </template>
      </a-table>
    </a-card>
    <a-card>
      <titleName title="基本信息"></titleName>
      <a-form-model
        ref="ruleForm"
        :model="form"
        :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
        :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
      >
        <a-row :gutter="24">
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item label="所属分公司">
              <SelectSubCompany
                placeholder="请选择"
                v-model="form.branchComId"
                disabled
              ></SelectSubCompany>
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item label="所属项目">
              <SelectProject
                placeholder="请选择"
                v-model="form.projectId"
                :form="form"
                :isClear="id == ''"
                keyValue="branchComId"
                disabled
              ></SelectProject>
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="退回申请人"
              prop="returnApplierId"
            >
              <a-select
                disabled
                placeholder="请选择"
                v-model="form.returnApplierId"
              >
                <a-spin
                  v-if="fetchingOrganizePeopleList"
                  slot="notFoundContent"
                  size="small"
                />
                <a-select-option
                  v-for="i in organizePeopleList"
                  :key="i.employeeId"
                  :value="i.employeeId"
                >{{ i.employeeName }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="银行账号"
              prop="bankAccount"
            >
              <BaseInput
                disabled
                placeholder="请输入"
                v-model="form.bankAccount"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="开户行名称"
              prop="accountBankName"
            >
              <BaseInput
                disabled
                placeholder="请输入"
                v-model="form.accountBankName"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item label="填报人">
              <BaseInput
                disabled
                placeholder="请输入"
                v-model="form.creatorName"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item label="填报时间">
              <BaseInput
                disabled
                placeholder="请输入"
                v-model="form.createTime"
              />
            </a-form-model-item>
          </a-col>

          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item label="附件">
              <file-link :fileList="form.fileInfoVOList"></file-link>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <a-card>
      <titleName title="公司财务资金部意见"></titleName>
      <a-form-model
        ref="ruleForm1"
        :model="form.financeAuditVO"
        :rules="rules1"
        :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
        :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
      >
        <a-row :gutter="24">
          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item
              label=""
              class="item"
            >
              该同志原有项目风险金按《项目部人员风险金预留分配表》中核定的金额
              <a-form-model-item
                :colon="false"
                label=" "
                prop="creditReturnAmount"
                :style="{ display: 'inline-block' }"
              >
                <a-input-number
                  :min="0"
                  :disabled="taskDefKey == 'GS_SWGLBJL_AUDIT'"
                  style="width: 350px; margin-top: -34px"
                  placeholder="请输入"
                  v-model="form.financeAuditVO.creditReturnAmount"
                />
              </a-form-model-item>
              元已全部预留。
            </a-form-model-item>
          </a-col>
          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item
              label="审批意见"
              prop="financeOpinions"
            >
              <BaseTextarea
                :disabled="taskDefKey == 'GS_SWGLBJL_AUDIT'"
                placeholder="请输入"
                v-model="form.financeAuditVO.financeOpinions"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <!-- v-if="taskDefKey == 'GS_SWGLBJL_AUDIT'" -->
    <a-card v-if="taskDefKey == 'GS_SWGLBJL_AUDIT'">
      <titleName title="公司商务管理部"></titleName>
      <a-form-model
        ref="ruleForm2"
        :model="form.commercialAuditVO"
        :rules="rules2"
        :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
        :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
      >
        <a-row :gutter="24">
          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item
              label=""
              class="item"
            >
              根据《商务管理手册》规定，建议将该同志原来在项目预留风险金
              <a-form-model-item
                :colon="false"
                label=" "
                prop="returnAmount"
                :style="{ display: 'inline-block' }"
              >
                <a-input-number
                  :min="0"
                  style="width: 350px; margin-top: -34px"
                  placeholder="请输入"
                  v-model="form.commercialAuditVO.returnAmount"
                />
              </a-form-model-item>
              元退回本人。
            </a-form-model-item>
          </a-col>
          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item
              label="审批意见"
              prop="commercialOpinions"
            >
              <BaseTextarea
                placeholder="请输入"
                v-model="form.commercialAuditVO.commercialOpinions"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <ApprovalDetails
      :title="'审批流程信息'"
      :business-id="id"
      :visible="visibleState.auditProcess"
      @cancel="visibleState.auditProcess = false"
      @confirm="visibleState.auditProcess = false"
    />
  </base-breadcrumb>
</template>
<script>
import ApprovalDetails from '@/components/approvalDetails'
import { addPersonalFinanceAudit, addPersonalCommercialAudit, checkPersonalRiskReturn } from '@/api/businessAffairs/riskRefund'
import { getOrganizePeopleList } from '@/api/safetySupervision/emergencyDrill'
import { getOrgEmployeesListBy } from '@/api/commons'
import { getProcessNodeList, completeTask } from '@/api/process'
import { getSelectListByType } from '@/api/businessAffairs/common.js'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import Consultation from '@/views/matters/approval/components/consultation'
import { isAttachment } from '@/utils/util'
import Vue from 'vue'
import moment from 'moment'
import UploadList from '@/components/UploadList'

const columnApprove = [
  {
    title: '序号',
    width: 80,
    align: 'center',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '审批人',
    dataIndex: 'userName',
    ellipsis: true,
    width: 180
  },
  {
    title: '审批时间',
    dataIndex: 'endTime',
    ellipsis: true,
    width: 180
  },
  {
    title: '节点名称',
    dataIndex: 'taskName',
    ellipsis: true,
    width: 180
  },
  {
    title: '滞留时间',
    dataIndex: 'durationInMillis',
    ellipsis: true,
    width: 140
  },
  {
    title: '审批意见',
    dataIndex: 'formData.opinions',
    scopedSlots: { customRender: 'opinions' },
    ellipsis: true
  }
]
export default {
  name: 'a' + Date.now(),
  components: {
    SelectSubCompany,
    SelectProject,
    UploadList,
    ApprovalDetails,
    Consultation
  },
  data() {
    const validator = (rule, value, callback) => {
      console.log(value)
      if (!value[0]) {
        callback(new Error('请输入风险金百分比！'))
      } else if (!value[1]) {
        callback(new Error('请输入风险金额度！'))
      } else {
        callback()
      }
    }
    return {
      visibleState: {
        auditProcess: false
      },
      loading: {
        PASS: false,
        REJECT: false
      },
      form: { financeAuditVO: {}, commercialAuditVO: {} },
      rules1: {
        creditReturnAmount: [{ required: true, message: '请输入' }],
        financeOpinions: [{ required: true, message: '请输入' }]
      },
      rules2: {
        returnAmount: [{ required: true, message: '请输入' }],

        commercialOpinions: [{ required: true, message: '请输入' }]
      },
      fetchingOrganizePeopleList: false,
      organizePeopleList: [],
      id: '',
      isSubmit: true,
      pageType: '',
      approveInfos: [], // 审批流程信息
      procInstId: '', //当前流程实例ID
      taskId: '', //当前流程节点ID
      processName: '', //流程名称
      taskName: '', //当前流程节点名称
      taskDefKey: '', //任务标识
      currentTime: '', //当前审批时间
      currentUser: '', //当前审批人
      flowRequesting: false,
      detailUrl: null, //详情地址

      assignType: '', //节点类型   0 变量获取 1 处理人 2 候选人 3 候选组 4 会签
      assignCode: '', //候选组编码 岗位编码
      assignLevel: '', //层级 项目部 PD 分公司 BC 公司 CO
      businessType: '', //业务类型 0 项目
      // 下级审批人
      subApproverList: [],
      // 流程表头
      columnApprove
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.$checkRequireItem()
      this.form.user = JSON.parse(sessionStorage.getItem('ycloud-user_info')).username
      this.id = this.$route.query.id
      const { type, code, level, btype, businessId, procInstId, name, processName, detailUrl, taskId, taskDefKey } = this.$route.query
      if (type) {
        this.assignType = type
        this.assignCode = code
        this.assignLevel = level
        this.businessType = btype
      }
      this.id = businessId
      // this.taskDefKey = 'GS_CWZJBJL_AUDIT'
      if (!this.id) {
        this.$error({ content: '无指定业务ID，将自动关闭' })
        setTimeout(() => {
          window.close()
        }, 1500)
        return
      }
      this.procInstId = procInstId
      this.currentUser = Vue.getAcloudProvider().getUserInfo()
      this.taskName = decodeURIComponent(name)
      this.processName = decodeURIComponent(processName)
      document.title = this.processName + '-' + this.taskName
      if (detailUrl) {
        this.detailUrl = decodeURIComponent(detailUrl)
      }
      this.taskId = taskId
      this.taskDefKey = taskDefKey

      this.currentTime = moment().format('yyyy-MM-DD HH:mm')
      this.$route.meta.title = '个人风险金返还审批'
      this.checkPersonalRiskReturnReq()
      //获取流程节点执行情况
      this.getProcessNodes()
    },
    //获取项目下的人员列表
    getOrganizePeopleList() {
      let params = {
        id: this.form.projectId
      }
      this.organizePeopleList = []
      this.fetchingOrganizePeopleList = true
      getOrganizePeopleList(params).then((res) => {
        this.fetchingOrganizePeopleList = false
        let obj = {}
        res.data = res.data.reduce((cur, next) => {
          obj[next.employeeId] ? '' : (obj[next.employeeId] = true && cur.push(next))
          return cur
        }, []) //设置cur默认类型为数组，并且初始值为空的数组
        console.log(res.data)
        this.organizePeopleList = res.data || []
      })

      console.log(this.organizePeopleList)
    },
    async checkPersonalRiskReturnReq() {
      const [err, res] = await checkPersonalRiskReturn({ id: this.id })
      if (!err) {
        res.data.commercialAuditVO = res.data.commercialAuditVO || {}
        res.data.financeAuditVO = res.data.financeAuditVO || {}
        this.form = res.data
        this.getOrganizePeopleList()
      }
    },

    validateForm1() {
      let flag = false
      this.$refs.ruleForm1.validate((valid) => {
        flag = valid
      })
      return flag
    },
    validateForm2() {
      let flag = false
      this.$refs.ruleForm2.validate((valid) => {
        flag = valid
      })
      return flag
    },
    // 处理增、删、改操作
    async handleSave(status) {
      if (this.loading[status]) return

      if (status == 'PASS') {
        if (this.taskDefKey == 'GS_CWZJBJL_AUDIT') {
          if (!this.validateForm1()) return

          this.handelApproval(status)
        } else if (this.taskDefKey == 'GS_SWGLBJL_AUDIT') {
          if (!this.validateForm2()) return

          this.handelApproval(status)
        }
      } else {
        this.handelUnApproval(status)
      }
    },
    handelUnApproval(staus) {
      // 审批不通过
      const _this = this
      const confirmWin = this.$confirm({
        title: '警告提醒！',
        content: '确定审批不通过？',
        okType: 'danger',
        onOk() {
          return new Promise((resolve, reject) => {
            _this
              .submit(true, staus)
              .then(() => {
                resolve()
                confirmWin.destroy()
              })
              .catch(() => reject)
          }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
        },
        onCancel() {}
      })
    },

    handelApproval(staus) {
      // 审批通过
      const _this = this
      const confirmWin = this.$confirm({
        title: '警告提醒！',
        content: '确定审批通过？',
        okType: 'danger',
        onOk() {
          return new Promise((resolve, reject) => {
            _this
              .submit(false, _this.createApproverList(_this.subApproverList))
              .then(() => {
                resolve()
                confirmWin.destroy()
              })
              .catch(() => reject)
          }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
        },
        onCancel() {}
      })
    },
    notifyParent() {
      window.opener.postMessage('finish', window.location.origin)
    },
    /**
     * @description: 组装下级审批人数据
     * @param {array} subApproverList 下级审批人表格数据
     * @return {object} 下级审批人数据
     */
    createApproverList(subApproverList) {
      const subordinateApproverList = {}
      subApproverList.forEach((item) => {
        if (item?.approver && item.approver.length > 0) {
          subordinateApproverList[item.taskInfo.id] = {
            assgins: item.approver?.map((el) => el.key).join(','),
            assignTypeEnum: 2
          }
        }
      })
      return subordinateApproverList
    },
    async submit(reject) {
      const params = {
        ...this.form
      }
      if (this.taskDefKey == 'GS_CWZJBJL_AUDIT' && !reject) {
        params.financeAuditVO.id = this.id
        const [err, res] = await addPersonalFinanceAudit(params.financeAuditVO)
      } else if (this.taskDefKey == 'GS_SWGLBJL_AUDIT' && !reject) {
        params.commercialAuditVO.id = this.id
        const [err, res] = await addPersonalCommercialAudit(params.commercialAuditVO)
      }
      const data = {
        formData: {
          opinions: this.taskDefKey == 'GS_CWZJBJL_AUDIT' ? this.form.financeAuditVO.financeOpinions : this.form.commercialAuditVO.commercialOpinions,
          reject
        },
        procInstId: this.procInstId,
        taskId: this.taskId,
        userId: this.currentUser.id
      }
      if (reject) {
        data['variables'] = { reject: true }
      }
      return completeTask(data)
        .then((res) => {
          if (res.status === 200) {
            this.notifyParent() // 通知父窗口
            // this.$success({
            //   content: '审批提交成功，即将自动关闭当前窗口',
            //   onOk() {
                window.close()
            //   }
            // })
            // setTimeout(() => {
            //   window.close()
            // }, 2000)
          } else {
            this.$error({ content: '审批提交失败，请稍后重试' })
          }
          return res
        })
        .catch((err) => {
          return err
        })
    },
    /**
     * @description: 获取流程信息
     * @return {void}
     */    
    getProcessNodes() {
      this.flowRequesting = true
      getProcessNodeList({ procInstId: this.procInstId, pageNo: 1, pageSize: 100 })
        .then((res) => {
          if (res.code === 200) {
            const data = res.data
            const userIds = data.map((d) => {
              if (d.formData) {
                d.formData = JSON.parse(d.formData)
              }
              return d.assignee
            })
            getOrgEmployeesListBy({ userIds, delete: true }).then((employees) => {
              this.flowRequesting = false
              res.data.forEach((r) => {
                employees.data.some((e) => {
                  if (e.userId === r.assignee) {
                    r.userName = e.name
                    return true
                  }
                })
              })
              this.approveInfos = res.data.map((el, index) => {
                el.key = index
                return el
              })
              console.log(res.data)
            })
          }
        })
        .catch(() => {
          this.flowRequesting = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
  display: flex;
  justify-content: flex-end;
  @{deep} .ant-btn + .ant-btn {
    margin-left: 12px;
  }
}
.tx {
  color: rgba(0, 0, 0, 0.85);
  font-size: 14px;
  margin-left: 30px;
}
.return-ratio .ant-form-item-children .ant-form-explain {
  margin-left: 230px;
}
.item {
  margin-left: 60px;
}
.item .ant-form-item {
  margin-top: -28px;
}
</style>